package entityData

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-next-entity/nextEntity"
	"strings"
)

type corp struct {
}

func (e *corp) QueryEntityById(id int64) (*nextEntity.CorpEntity, error) {
	entity, err := commSql.QueryEntityById(nextEntity.Type.CorpEntity.Type(), id)
	if err != nil {
		return nil, err
	}
	return entity.(*nextEntity.CorpEntity), nil
}

func (e *corp) QueryEntityByKey(corpName string) (*nextEntity.CorpEntity, error) {
	sql := "SELECT * FROM tb_corp  WHERE corp_name = '" + corpName + "'"
	list, err := commSql.Query(nextEntity.Type.CorpEntity.Type(), sql)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return nil, nil
	}

	return list[0].(*nextEntity.CorpEntity), nil
}

func (e *corp) Do() error {
	mtsql := `SELECT * from tb_corp s1 WHERE s1.corp_data->'$.web' LIKE '"http://http://%'`
	count, err := commSql.QueryCount(commSql.SqlBuilder.BuildSelectCount(mtsql))
	if err != nil {
		return err
	}

	pageSize := 100
	pageCount := count / pageSize
	if count%pageSize > 0 {
		pageCount += 1
	}

	for pageNum := 1; pageNum <= pageCount; pageNum++ {
		sql := commSql.SqlBuilder.BuildSelectPage(nextEntity.Type.CorpEntity.TableName(), nil, nil, mtsql, pageNum, pageSize)
		list, err := commSql.Query(nextEntity.Type.CorpEntity.Type(), sql)
		if err != nil {
			return err
		}

		for _, val := range list {
			entity := val.(*nextEntity.CorpEntity)
			if !Map.Has(entity.Data, "web") {
				continue
			}

			web := Map.GetString(entity.Data, "web", "")
			if web != "" {
				web = strings.Replace(web, "http://https://", "https://", 1)
				web = strings.Replace(web, "http://http://", "http://", 1)
				web = strings.TrimSpace(web)
				if strings.HasSuffix(web, "/") {
					web = web[:len(web)-1]
				}
				entity.Data["web"] = web
			}

			commSql.UpdateEntityById(entity)
		}
	}

	return nil
}

func (e *corp) QueryEntityByKeys(corpNames []string) (map[string]*nextEntity.CorpEntity, error) {
	result := make(map[string]*nextEntity.CorpEntity, 0)
	if len(corpNames) == 0 {
		return result, nil
	}

	// 构造SQL语句和参数列表
	args := make([]interface{}, 0)
	sb := strings.Builder{}
	sb.WriteString("SELECT * FROM tb_corp  WHERE company_name in (")
	for idx, name := range corpNames {
		args = append(args, name)

		sb.WriteString("?")
		if idx < len(corpNames)-1 {
			sb.WriteString(",")
		} else {
			sb.WriteString(")")
		}
	}
	sql := sb.String()

	list, err := commSql.SQuery(nextEntity.Type.CorpEntity.Type(), sql, args)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return result, nil
	}

	for _, val := range list {
		entity := val.(*nextEntity.CorpEntity)

		result[entity.MakeServiceKey()] = entity
	}

	return result, nil
}

func (e *corp) SyncEntityByKeys(list []map[string]interface{}, merge Merge) error {
	// 名称数组
	names := make([]string, 0)
	for _, data := range list {
		name := Map.GetString(data, "companyName", "")
		if name == "" {
			continue
		}
		names = append(names, name)
	}

	// 根据名称查询数据
	exists, err := e.QueryEntityByKeys(names)
	if err != nil {
		return err
	}

	for _, data := range list {
		name := Map.GetString(data, "companyName", "")
		if name == "" {
			continue
		}
		entity := nextEntity.Type.CorpEntity.NewEntity().(*nextEntity.CorpEntity)
		entity.CompanyName = name

		exist := exists[entity.MakeServiceKey()]
		if exist == nil {
			e.mergeField(entity, data)
			e.mergeData(entity.Data, data, merge)

			commSql.InsertEntity(entity)
		} else {
			e.mergeField(exist, data)
			if !e.mergeData(exist.Data, data, merge) {
				continue
			}

			commSql.UpdateEntityById(exist)
		}
	}

	return nil
}

func (e *corp) mergeField(entity *nextEntity.CorpEntity, src map[string]interface{}) {
	province := Map.GetString(src, "province", "")
	city := Map.GetString(src, "city", "")
	industry := Map.GetString(src, "industry", "")
	companyType := Map.GetString(src, "companyType", "")
	companyName := Map.GetString(src, "companyName", "")

	if companyName != "" {
		entity.CompanyName = companyName
	}
	if province != "" {
		entity.Province = province
	}
	if city != "" {
		entity.City = city
	}
	if industry != "" {
		entity.Industry = industry
	}
	if companyType != "" {
		entity.CompanyType = companyType
	}
}

func (e *corp) mergeData(data map[string]interface{}, src map[string]interface{}, merge Merge) bool {
	result := false
	if e.mergeValue(data, src, "position", merge) {
		result = true
	}
	if e.mergeValue(data, src, "legalPersonName", merge) {
		result = true
	}
	if e.mergeValue(data, src, "regCapital", merge) {
		result = true
	}
	if e.mergeValue(data, src, "regLocation", merge) {
		result = true
	}
	if e.mergeValue(data, src, "businessScope", merge) {
		result = true
	}
	if e.mergeValue(data, src, "postalCode", merge) {
		result = true
	}

	if e.mergeValue(data, src, "officeLocation", merge) {
		result = true
	}
	if e.mergeValue(data, src, "web", merge) {
		result = true
	}
	if e.mergeValue(data, src, "contacts", merge) {
		result = true
	}
	if e.mergeValue(data, src, "tel", merge) {
		result = true
	}
	if e.mergeValue(data, src, "mobile", merge) {
		result = true
	}
	if e.mergeValue(data, src, "fax", merge) {
		result = true
	}
	if e.mergeValue(data, src, "dataSource", merge) {
		result = true
	}

	return result
}

// mergeValue 合并数值：如果有新的输入数据，那么合并数据
func (e *corp) mergeValue(data map[string]interface{}, src map[string]interface{}, key string, merge Merge) bool {
	val, ok := src[key]
	if !ok {
		return false
	}
	if val == "" {
		return false
	}

	// 追加模式：如果原来数据存在，那么不写入
	if merge == MergeAppend && data[key] != nil {
		return false
	}

	if data[key] == src[key] {
		return false
	}

	data[key] = src[key]
	return true
}
